﻿using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Filters;
using Newtonsoft.Json.Serialization;
using Owin;
using SuperSocket.SocketBase;
using SuperSocket.WebSocket;

namespace Aecg.OwinSelfHostServer.Service
{
    public class Startup
    {
        /// <summary>
        ///     处理404 路由
        /// </summary>
        public virtual void SetNotFoundRoute(HttpConfiguration configuration)
        {
            #region 404 全局处理

            configuration.Routes.MapHttpRoute(
                "NotFound",
                "{*path}",
                new {controller = "Error", action = "NotFound"});

            #endregion
        }

        /// <summary>
        ///     Specifies how the ASP.NET application will respond to individual HTTP request.
        /// </summary>
        /// <param name="app">Instance of <see cref="IAppBuilder" />.</param>
        public virtual void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();


            #region 替换默认Json序列化工具

            configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);
            configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver(); //默认驼峰
            configuration.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

            #endregion


            configuration.MapHttpAttributeRoutes();

            SetNotFoundRoute(configuration);


            #region websocketServerInit

            var server = new WebSocketServer();
            server.NewSessionConnected += server_NewSessionConnected;

            server.NewMessageReceived += server_NewMessageReceived;
            server.SessionClosed += server_SessionClosed;

            server.Setup("127.0.0.1", 9001); //设置端口  
            server.Start(); //开启监听 

            #endregion


            ReplaceHttpErrorHandler(configuration);
            app.UseWebApi(configuration);
        }

        public virtual void ReplaceHttpErrorHandler(HttpConfiguration config)
        {
            config.EnableCors(new EnableCorsAttribute("*", "*", "*")); //todo 安全考虑要配置支持哪些域名跨域  支持跨域()
            var filter = config.Filters.FirstOrDefault(f => f.Instance is IExceptionFilter);
            var handler = new ErrorFilterAttribute();

            if (filter != null)
            {
                if (filter.Instance is ErrorFilterAttribute)
                    return;

                config.Filters.Remove(filter.Instance);

                handler.WrappedFilter = (IExceptionFilter) filter.Instance;
            }

            config.Filters.Add(handler);
        }

        #region test

        private static void server_SessionClosed(WebSocketSession session, CloseReason value)
        {
            Console.WriteLine(session.Origin);
        }

        private static void server_NewMessageReceived(WebSocketSession session, string value)
        {
            Console.WriteLine(value);
            session.Send(value);
        }

        private static void server_NewSessionConnected(WebSocketSession session)
        {
            session.Send("成功连接！");
        }

        #endregion
    }
}